// 
//  player.js
//  firefox
//  
//  Created by Zak on 2008-06-18.
//  Copyright 2008 Ant.com. All rights reserved.
// 

/**
 * AntPlayer: Handle all actions inside the player.xul window
 */
top.AntPlayer =
{
    doc: null,
    listBox: null,
	currentVideo: "",
	flashVars: "&javascriptid=antFlvPlayerSwf&enablejs=true&backcolor=0xFFFFFF&autostart=true&autoscroll=true&searchbar=false",

    /**
     * Initialize the list
     * @param doc           The document window
     */
    init: function (doc)
    {
        // AntLib.toLog("AntPlayer: init");
        this.doc = doc;
        this.listBox = $('antFlvPlayerRichListBox', doc);
		this.antSplash();
		this.fillVideos();

		window.addEventListener("load", this.autoPlay(), false);
		//unload because the movie keep running when leaving the player with a bookmark link
		var that = this;
		window.addEventListener("unload", function (){ that.antSplash(); }, false);
		window.addEventListener("resize", function (){ that.playVideo(that.currentVideo, true); }, false);
    },
	
	/**
	 * Auto play a video when the player loads using preference or trying to guess the last download
	 */
	autoPlay: function ()
	{
	    // AntLib.toLog("AntPlayer: autoPlay");
		var that = this;
		return function ()
		{
			var splitter = $("antFlvPlayerSplitter");
			var embed = $("antFlvPlayerEmbed");
		    var file = CCIN("@mozilla.org/file/local;1", "nsILocalFile");

			splitter.addEventListener("mouseup", function (){ that.playVideo(that.currentVideo, true); }, true);

        	file.initWithPath(AntPrefs.flvToPlay());
        	if (!file.exists() || !AntPrefs.flvToPlay())
        	{
                var index = that.listBox.getIndexOfFirstVisibleRow();
                var nodes = that.listBox.childNodes[index].childNodes;
                
                that.playVideo(nodes[1].getAttribute('label'));
        	}
        	else
        	{
        	    that.playVideo(AntPrefs.flvToPlay());
        	}

		}
	},

    /**
     * getItemByUrl
     */
    colorItemByUrl: function (url)
    {
		for (var i = 0; i < this.listBox.childNodes.length; i++)
		{
		    var item = this.listBox.childNodes[i];
            var className = "antFlvPlayerRichListItem";

			if (!item)
				return;
			if (url == item.path)
			{
			    className = item.getAttribute('class') + " antFlvPlayerRichListItemActive";
				item.setAttribute('class', className); 
			}
			else
			{
                if ((i % 2) == 0)
                    className += " antFlvPlayerRichListItemGrey";
                item.setAttribute('class', className);
            }
		}
		return null;
    },

    
    /**
     * Handle search using terms typed in the antToolBarSearchBox
     * @param event         The event that triggered the call to this callback
     * @param type          The type of search (web,image,video,news,blog)
     */
    doSearch: function (type)
    {
        var searchTermsBox = $("antFlvPlayerSearchBox");
        var searchTerms = searchTermsBox.value.trim();

        if (searchTerms.length == 0)
        {
            AntLib.openURL('http://www.ant.com/');
        }
        else
        {
            searchTerms = AntLib.uriEncode(searchTerms);
            AntLib.openURL('http://www.ant.com/'+type+'/'+searchTerms);
        }
    },
    
    /**
     * Clear the searchbox the first time user enter it
	 * @param isFocus true if the callback is onFocus otherwise false
     */
    onSearchBoxOnFocus: function (isFocus)
    {
        var searchBox = $('antFlvPlayerSearchBox');
        
        if (!cleanedSearchBox && isFocus)
        {
            searchBox.value = '';
            cleanedSearchBox = true;
        }
		
		if (!isFocus && !searchBox.value)
		{
            searchBox.value = 'Search the web';
            cleanedSearchBox = false;
		}
    },

    /**
     * Handle keystrokes entered in the searchBox
     * @param event         The event that triggered the call to this function
     */
    onSearchBoxKeyPress: function (event)
    {
        if (event.keyCode == event.DOM_VK_RETURN && $('antFlvPlayerSearchBox').value != '')
        	this.doSearch('web');
    },

	/**
	 * Display the Splash Screen
	 */
	antSplash: function ()
	{
		var embed = $("antFlvPlayerEmbed");
		
        embed.setAttribute("flashvars", "file=chrome://antbar/content/player/skin/img/ant.jpg&image=chrome://antbar/content/player/skin/img/ant.jpg&shownavigation=false&javascriptid=antFlvPlayerSwf&enablejs=true&frontcolor=0xFFFFFF&lightcolor=0xFFFFFF&screencolor=0xFFFFFF&searchbar=false&showicons=false&shownavigation=false");
        $("antFlvPlayerContentBox").removeChild($("antFlvPlayerContentBox").firstChild);
		$("antFlvPlayerContentBox").insertBefore(embed, $("antFlvPlayerSplitter"));
		$("antFlvPlayerTitleBar").innerHTML = AntLang.getFormatString("AntPlayer.TitleBar", "Ant.com", "Player");
    },

    formatDisplayStrings: function (flvlink)
    {
        var humanizedName = flvlink.name.replace(/_/g, ' ');
        var infosString = flvlink.origin;

        infosString = infosString.upFirstLetter();
        humanizedName = humanizedName.upFirstLetter();
        if (flvlink.filesize)
            infosString += " - " + flvlink.filesize;
        if (flvlink.date)
        {
            var date = new Date(flvlink.date);
            var day = date.getDate();
            var month = date.getMonth();
            var year = date.getFullYear();
            var hour = date.getHours();
            var minute = date.getMinutes();
            var formatedHour = day+"/"+month+"/"+year+" "+hour+":"+minute;

			infosString += " - " + formatedHour;
        }

        return [humanizedName, infosString];
    },

    /**
     * Add a ListItem to the ListBox
     * @param origin        Origin of the flv
     * @param url           Url of the flv
     * @param name          Guessed name of the flv
     * @param id            A unique ID for the listItem
     */
    appendItem: function (flvlink, id)
    {
        var className = "antFlvPlayerRichListItem";
        var richListItem = this.doc.createElement('richlistitem');
        var nameLabel = this.doc.createElement('label');
        var originLabel = this.doc.createElement('label');
        var strings = this.formatDisplayStrings(flvlink);

        if ((id % 2) == 0)
            className += " antFlvPlayerRichListItemGrey";
        richListItem.setAttribute('class', className);
        richListItem.setAttribute('ondblclick', 'AntPlayer.onListItemDblClick(event);');
        richListItem.setAttribute('context', "antFlvPlayerPopupMenu");
        richListItem.setAttribute('orient', "vertical");
		richListItem.path = flvlink.url;

        nameLabel.setAttribute('value', strings[0]);
        nameLabel.setAttribute('class', 'antFlvPlayerRichListName');
        nameLabel.setAttribute('crop', 'end');

        originLabel.setAttribute('value', strings[1]);
        originLabel.setAttribute('class', 'antFlvPlayerRichListInfos');
        originLabel.setAttribute('crop', 'end');

        richListItem.appendChild(nameLabel);
        richListItem.appendChild(originLabel);

        this.listBox.appendChild(richListItem);
    },
    
    
    /**
     * Redraw the iframe with needed parameters to play the specified file
     * @param path      The full file path to play (Format: /tmp/origin.name.flv)
     */
    playVideo: function (path)
    {
		var embed = $("antFlvPlayerEmbed");

		embed.setAttribute("flashvars", "file=file://" + path + this.flashVars);
		$("antFlvPlayerContentBox").removeChild($("antFlvPlayerContentBox").firstChild);
		$("antFlvPlayerContentBox").insertBefore(embed, $("antFlvPlayerSplitter"));

		try
		{
			var file = CCIN("@mozilla.org/file/local;1", "nsILocalFile");
			file.initWithPath(path);

			var origin = AntLib.extractFlvOrigin(file.leafName);
			var name = AntLib.extractFlvName(file.leafName);

			name = name.replace(/_/g, " ");
			$("antFlvPlayerTitleBar").innerHTML = AntLang.getFormatString("AntPlayer.TitleBar", origin, name);
		}
		catch (e)
		{}

		this.currentVideo = path;
		this.colorItemByUrl(path);
    },

    /**
     * Oncommand Logo Click
     */
    onLogoClick: function ()
    {
        AntLib.openURL('http://www.ant.com/');
    },

    /**
     * Callback: fired when the user double click an item in the list
     * @param event     The event that triggered the call to this method
     */
    onListItemDblClick: function (event)
    {
        var node = event.target;
		
		while (node.nodeName != "richlistitem")
			node = node.parentNode;
        this.playVideo(node.path);
    },

    /**
     * Callback: fired when the user click on "Play" in the context menu
     */
    onPopupPlay: function ()
    {
		var node = document.popupNode;
		
		while (node.nodeName != "richlistitem")
			node = node.parentNode;
        this.playVideo(node.path);
    },

    /**
     * Callback: fired when the user click on "Rename" in the context menu
     */
    onPopupRename: function ()
    {
    	var node = document.popupNode;

		while (node.nodeName != "richlistitem")
			node = node.parentNode;
        var path = node.path;
		var file = CCIN("@mozilla.org/file/local;1", "nsILocalFile");

		file.initWithPath(path);

		var origin = AntLib.extractFlvOrigin(file.leafName);
		var name = AntLib.extractFlvName(file.leafName);
		if (this.isCurrentlyPlaying(file.path))
			return ;

		name = name.replace(/_/g,' ');
		var newName = prompt(AntLang.getFormatString("AntPlayer.PromptRename", name), name);

		if (!newName)
			return ;

		if (!newName.match(/^[\w -]+$/i))
		{
			alert(AntLang.getString("AntPlayer.InvalidFileName"));
			return
		}
		newName = newName.sanitize();
		if (file.exists())
		{
			try
			{
				file.moveTo(file.parent, origin + "." + newName + ".flv");
			}
			catch (e)
			{
				alert(AntLang.getString("AntPlayer.ErrorRenaming"));
				return ;
			}
		}
		this.fillVideos();
    },


	/**
	 * Check if the given video path is currently playing
	 * @param path          The path to check
	 */
	isCurrentlyPlaying: function (path)
    {
		if (this.currentVideo == path)
		{
			alert(AntLang.getString("AntPlayer.ErrorCurrentlyPlaying"));
			return true;
		}

		return false;
	},

    /**
     * Callback: fired when the user click on "Delete" in the context menu
     */
    onPopupDelete: function ()
    {
    	var node = document.popupNode;

		while (node.nodeName != "richlistitem")
			node = node.parentNode;
        var path = node.path;
		var file = CCIN("@mozilla.org/file/local;1", "nsILocalFile");
		var name;

		file.initWithPath(path);
		name = AntLib.extractFlvName(file.leafName);

        if (confirm(AntLang.getFormatString("AntPlayer.ConfirmDelete", name)))
		{
            if (this.currentVideo == path)
                this.antSplash();
            try  {
             file.remove(false);
            }
            catch (e) {
             alert(AntLang.getString("AntPlayer.ErrorDeleting"));
             AntLib.toLog("ERROR: AntPlayer.onPopupDelete: " + e);
             return ;
            }
            this.fillVideos();
		}
    },

    /**
     * Remove all listItems from the ListBox
     */
    removeAll: function ()
    {
		while (this.listBox.childNodes.length > 0)
			this.listBox.removeChild(this.listBox.childNodes.item(0));
    },

    /**
     * Fetch videos from a directory and return an Array of AntFlvLink
     */
	fetchVideos: function ()
	{
		var pref = AntPrefs.getAntBranch();
		if (!pref)
		{
			alert(AntLang.getString("AntDownloadManager.InvalidDestinationFolder"));
			return null;
		}
		var dir = pref.getCharPref("flvdir");
		var videoDirectory = CCIN("@mozilla.org/file/local;1", "nsILocalFile");
		var entries;
		var arr = new AntArray();

		videoDirectory.initWithPath(dir);
		if (!videoDirectory.isDirectory())
			return new AntArray();

		entries = videoDirectory.directoryEntries;
		while (entries.hasMoreElements())
		{
			var entry = entries.getNext();

			QI(entry, CI("nsIFile"));
			if (entry.leafName.match(/^[\w-]+\.[\w-]+\.flv$/i))
			{
				var index = entry.leafName.indexOf(".");
				var origin = entry.leafName.substring(0, index > -1 ? index : 0);
				var url = entry.path;
				var name = "";
				var lastModifiedTime = entry.lastModifiedTime
                var filesize = AntLib.convertByteUnits(entry.fileSize);

				index = entry.leafName.lastIndexOf(".");
				name = entry.leafName.substring(origin.length + 1, index > -1 ? index : 0);
				arr.push(new AntFlvLink({origin: origin, url:url, name:name, date:lastModifiedTime, filesize:filesize[0] + " " + filesize[1]}));
			}
		}
		
		return arr;
	},

    /**
     * Fill the list with the videos
     */
	fillVideos: function ()
	{
		if (this.listBox.childNodes.length > 0)
			this.removeAll();
		var listVideos = this.fetchVideos();

		for (var i = 0; i < listVideos.length; i++)
			this.appendItem(listVideos[i], i);
	},
}
